#include "btreeInt.h"

/*
 **************************************************************************
 **************************************************************************
 ** 
 ** sqlite3Btree functions
 ** 
 **************************************************************************
 **************************************************************************
 */

/*
 ** Set this global variable to 1 to enable tracing using the TRACE
 ** macro.
 */
#if 0
int sqlite3BtreeTrace=1;  /* True to enable tracing */
# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
#else
# define TRACE(X)
#endif


/*
 ** Clear the current cursor position.
 */
void sqlite3BtreeClearCursor(BtCursor *pCur){
	/* TODO : Implement */
	assert(0);
}

/*
 ** Determine whether or not a cursor has moved from the position it
 ** was last placed at.  Cursors can move when the row they are pointing
 ** at is deleted out from under them.
 **
 ** This routine returns an error code if something goes wrong.  The
 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
 */
int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
	int rc = SQLITE_OK;
	
	/* TODO : Implement */
	assert(0);
	//*pHasMoved = 0;
	//*pHasMoved = 1;
	return rc;
}

/*
 ** Open a database file.
 ** 
 ** zFilename is the name of the database file.  If zFilename is NULL
 ** then an ephemeral database is created.  The ephemeral database might
 ** be exclusively in memory, or it might use a disk-based memory cache.
 ** Either way, the ephemeral database will be automatically deleted 
 ** when sqlite3BtreeClose() is called.
 **
 ** If zFilename is ":memory:" then an in-memory database is created
 ** that is automatically destroyed when it is closed.
 **
 ** The "flags" parameter is a bitmask that might contain bits
 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
 ** These flags are passed through into sqlite3PagerOpen() and must
 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
 **
 ** If the database is already opened in the same database connection
 ** and we are in shared cache mode, then the open will fail with an
 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
 ** objects in the same database connection since doing so will lead
 ** to problems with locking.
 */
int sqlite3BtreeOpen(
					 const char *zFilename,  /* Name of the file containing the BTree database */
					 sqlite3 *db,            /* Associated database handle */
					 Btree **ppBtree,        /* Pointer to new Btree object written here */
					 int flags,              /* Options */
					 int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
					 ){
	int rc = SQLITE_OK;            /* Result code from this function */
	/* TODO : Implement */
	assert(0);

	// return SQLITE_NOMEM;
	// return SQLITE_CONSTRAINT;
	return rc;
}

/*
 ** Close an open database and invalidate all cursors.
 */
int sqlite3BtreeClose(Btree *p){
	/* TODO : Implement */
	assert(0);
	
	return SQLITE_OK;
}

/*
 ** Change the limit on the number of pages allowed in the cache.
 **
 ** The maximum number of cache pages is set to the absolute
 ** value of mxPage.  If mxPage is negative, the pager will
 ** operate asynchronously - it will not stop to do fsync()s
 ** to insure data is written to the disk surface before
 ** continuing.  Transactions still work if synchronous is off,
 ** and the database cannot be corrupted if this program
 ** crashes.  But if the operating system crashes or there is
 ** an abrupt power failure when synchronous is off, the database
 ** could be left in an inconsistent and unrecoverable state.
 ** Synchronous is on by default so database corruption is not
 ** normally a worry.
 */
int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
	int rc = SQLITE_OK;
	/* TODO : Implement */
	assert(0);
	// sqlite3PagerSetCachesize(pBt->pPager, mxPage);
	return rc;
}

/*
 ** Change the way data is synced to disk in order to increase or decrease
 ** how well the database resists damage due to OS crashes and power
 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
 ** there is a high probability of damage)  Level 2 is the default.  There
 ** is a very low but non-zero probability of damage.  Level 3 reduces the
 ** probability of damage to near zero but with a write performance reduction.
 */
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
int sqlite3BtreeSetSafetyLevel(
							   Btree *p,              /* The btree to set the safety level on */
							   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
							   int fullSync,          /* PRAGMA fullfsync. */
							   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
							   ){
	int rc = SQLITE_OK;
	/* TODO : Implement */
	assert(0);
	//sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
	return rc;
}
#endif

/*
 ** Return TRUE if the given btree is set to safety level 1.  In other
 ** words, return TRUE if no sync() occurs on the disk files.
 */
int sqlite3BtreeSyncDisabled(Btree *p){
	int rc = SQLITE_OK;
	/* TODO : Implement */
	assert(0);
	// rc = sqlite3PagerNosync(pBt->pPager);
	return rc;
}

#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
/*
 ** Change the default pages size and the number of reserved bytes per page.
 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
 ** without changing anything.
 **
 ** The page size must be a power of 2 between 512 and 65536.  If the page
 ** size supplied does not meet this constraint then the page size is not
 ** changed.
 **
 ** Page sizes are constrained to be a power of two so that the region
 ** of the database file used for locking (beginning at PENDING_BYTE,
 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
 ** at the beginning of a page.
 **
 ** If parameter nReserve is less than zero, then the number of reserved
 ** bytes per page is left unchanged.
 **
 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
 ** and autovacuum mode can no longer be changed.
 */
int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ 
	int rc = SQLITE_OK;
	/* TODO : Implement */
	assert(0);
	//return SQLITE_READONLY;
	//rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
	return rc;
}

/*
 ** Return the currently defined page size
 */
int sqlite3BtreeGetPageSize(Btree *p){
	/* TODO : Implement */
	assert(0);
	
	//return p->pBt->pageSize;
	return -1;
}

/*
 ** Set the maximum page count for a database if mxPage is positive.
 ** No changes are made if mxPage is 0 or negative.
 ** Regardless of the value of mxPage, return the maximum page count.
 */
int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
	int n = -1;

	/* TODO : Implement */
	assert(0);
	
	//n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
	return n;
}

/*
 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
 ** then make no changes.  Always return the value of the secureDelete
 ** setting after the change.
 */
int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
	int b = -1;

	//TODO : Implement
	assert(0);

	return b;
}
#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */

/*
 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
 ** is disabled. The default value for the auto-vacuum property is 
 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
 */
int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
#ifdef SQLITE_OMIT_AUTOVACUUM
	return SQLITE_READONLY;
#else
	int rc = SQLITE_OK;

	//TODO : Implement
	assert(0);

	// pBt->autoVacuum = av ?1:0;
	// pBt->incrVacuum = av==2 ?1:0;
	return rc;
#endif
}

/*
 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
 ** enabled 1 is returned. Otherwise 0.
 */
int sqlite3BtreeGetAutoVacuum(Btree *p){
#ifdef SQLITE_OMIT_AUTOVACUUM
	return BTREE_AUTOVACUUM_NONE;
#else
	int rc;
	//TODO : Implement
	assert(0);
    /*
	rc = (
		  (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
		  (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
		  BTREE_AUTOVACUUM_INCR
		  );
	 */
	return rc;
#endif
}

/*
 ** Attempt to start a new transaction. A write-transaction
 ** is started if the second argument is nonzero, otherwise a read-
 ** transaction.  If the second argument is 2 or more and exclusive
 ** transaction is started, meaning that no other process is allowed
 ** to access the database.  A preexisting transaction may not be
 ** upgraded to exclusive by calling this routine a second time - the
 ** exclusivity flag only works for a new transaction.
 **
 ** A write-transaction must be started before attempting any 
 ** changes to the database.  None of the following routines 
 ** will work unless a transaction is started first:
 **
 **      sqlite3BtreeCreateTable()
 **      sqlite3BtreeCreateIndex()
 **      sqlite3BtreeClearTable()
 **      sqlite3BtreeDropTable()
 **      sqlite3BtreeInsert()
 **      sqlite3BtreeDelete()
 **      sqlite3BtreeUpdateMeta()
 **
 ** If an initial attempt to acquire the lock fails because of lock contention
 ** and the database was previously unlocked, then invoke the busy handler
 ** if there is one.  But if there was previously a read-lock, do not
 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
 ** returned when there is already a read-lock in order to avoid a deadlock.
 **
 ** Suppose there are two processes A and B.  A has a read lock and B has
 ** a reserved lock.  B tries to promote to exclusive but is blocked because
 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
 ** One or the other of the two processes must give way or there can be
 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
 ** when A already has a read lock, we encourage A to give up and let B
 ** proceed.
 */
int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
	int rc = SQLITE_OK;

	//TODO : Implement
	assert(0);

	//rc = SQLITE_LOCKED_SHAREDCACHE;
	//rc = SQLITE_READONLY;
	return rc;
}

/*
 ** This routine does the first phase of a two-phase commit.  This routine
 ** causes a rollback journal to be created (if it does not already exist)
 ** and populated with enough information so that if a power loss occurs
 ** the database can be restored to its original state by playing back
 ** the journal.  Then the contents of the journal are flushed out to
 ** the disk.  After the journal is safely on oxide, the changes to the
 ** database are written into the database file and flushed to oxide.
 ** At the end of this call, the rollback journal still exists on the
 ** disk and we are still holding all locks, so the transaction has not
 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
 ** commit process.
 **
 ** This call is a no-op if no write-transaction is currently active on pBt.
 **
 ** Otherwise, sync the database file for the btree pBt. zMaster points to
 ** the name of a master journal file that should be written into the
 ** individual journal file, or is NULL, indicating no master journal file 
 ** (single database transaction).
 **
 ** When this is called, the master journal should already have been
 ** created, populated with this journal pointer and synced to disk.
 **
 ** Once this is routine has returned, the only thing required to commit
 ** the write-transaction for this database file is to delete the journal.
 */
int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Commit the transaction currently in progress.
 **
 ** This routine implements the second phase of a 2-phase commit.  The
 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
 ** routine did all the work of writing information out to disk and flushing the
 ** contents so that they are written onto the disk platter.  All this
 ** routine has to do is delete or truncate or zero the header in the
 ** the rollback journal (which causes the transaction to commit) and
 ** drop locks.
 **
 ** This will release the write lock on the database file.  If there
 ** are no active cursors, it also releases the read lock.
 */
int sqlite3BtreeCommitPhaseTwo(Btree *p){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Do both phases of a commit.
 */
int sqlite3BtreeCommit(Btree *p){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	/*
	rc = sqlite3BtreeCommitPhaseOne(p, 0);
	if( rc==SQLITE_OK ){
		rc = sqlite3BtreeCommitPhaseTwo(p);
	}
	*/
	return rc;
}

/*
 ** This routine sets the state to CURSOR_FAULT and the error
 ** code to errCode for every cursor on BtShared that pBtree
 ** references.
 **
 ** Every cursor is tripped, including cursors that belong
 ** to other database connections that happen to be sharing
 ** the cache with pBtree.
 **
 ** This routine gets called when a rollback occurs.
 ** All cursors using the same cache must be tripped
 ** to prevent them from trying to use the btree after
 ** the rollback.  The rollback may have deleted tables
 ** or moved root pages, so it is not sufficient to
 ** save the state of the cursor.  The cursor must be
 ** invalidated.
 */
void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
	// TODO : Implement
    assert(0);
}

/*
 ** Rollback the transaction in progress.  All cursors will be
 ** invalided by this operation.  Any attempt to use a cursor
 ** that was open at the beginning of this operation will result
 ** in an error.
 **
 ** This will release the write lock on the database file.  If there
 ** are no active cursors, it also releases the read lock.
 */
int sqlite3BtreeRollback(Btree *p){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Start a statement subtransaction. The subtransaction can can be rolled
 ** back independently of the main transaction. You must start a transaction 
 ** before starting a subtransaction. The subtransaction is ended automatically 
 ** if the main transaction commits or rolls back.
 **
 ** Statement subtransactions are used around individual SQL statements
 ** that are contained within a BEGIN...COMMIT block.  If a constraint
 ** error occurs within the statement, the effect of that one statement
 ** can be rolled back without having to rollback the entire transaction.
 **
 ** A statement sub-transaction is implemented as an anonymous savepoint. The
 ** value passed as the second parameter is the total number of savepoints,
 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
 ** are no active savepoints and no other statement-transactions open,
 ** iStatement is 1. This anonymous savepoint can be released or rolled back
 ** using the sqlite3BtreeSavepoint() function.
 */
int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	//rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
	
	return rc;
}

/*
 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
 ** savepoint identified by parameter iSavepoint, depending on the value 
 ** of op.
 **
 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
 ** contents of the entire transaction are rolled back. This is different
 ** from a normal transaction rollback, as no locks are released and the
 ** transaction remains open.
 */
int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	//rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
	return rc;
}

/*
 ** Create a new cursor for the BTree whose root is on the page
 ** iTable. If a read-only cursor is requested, it is assumed that
 ** the caller already has at least a read-only transaction open
 ** on the database already. If a write-cursor is requested, then
 ** the caller is assumed to have an open write transaction.
 **
 ** If wrFlag==0, then the cursor can only be used for reading.
 ** If wrFlag==1, then the cursor can be used for reading or for
 ** writing if other conditions for writing are also met.  These
 ** are the conditions that must be met in order for writing to
 ** be allowed:
 **
 ** 1:  The cursor must have been opened with wrFlag==1
 **
 ** 2:  Other database connections that share the same pager cache
 **     but which are not in the READ_UNCOMMITTED state may not have
 **     cursors open with wrFlag==0 on the same table.  Otherwise
 **     the changes made by this write cursor would be visible to
 **     the read cursors in the other database connection.
 **
 ** 3:  The database must be writable (not on read-only media)
 **
 ** 4:  There must be an active transaction.
 **
 ** No checking is done to make sure that page iTable really is the
 ** root page of a b-tree.  If it is not, then the cursor acquired
 ** will not work correctly.
 **
 ** It is assumed that the sqlite3BtreeCursorZero() has been called
 ** on pCur to initialize the memory space prior to invoking this routine.
 */
int sqlite3BtreeCursor(
					   Btree *p,                                   /* The btree */
					   int iTable,                                 /* Root page of table to open */
					   int wrFlag,                                 /* 1 to write. 0 read-only */
					   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
					   BtCursor *pCur                              /* Write new cursor here */
					   ){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Return the size of a BtCursor object in bytes.
 **
 ** This interfaces is needed so that users of cursors can preallocate
 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
 ** to users so they cannot do the sizeof() themselves - they must call
 ** this routine.
 */
int sqlite3BtreeCursorSize(void){
	// TODO : Implement
	assert(0);
	
	//return ROUND8(sizeof(BtCursor));
	return -1;
}

/*
 ** Initialize memory that will be converted into a BtCursor object.
 **
 ** The simple approach here would be to memset() the entire object
 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
 ** do not need to be zeroed and they are large, so we can save a lot
 ** of run-time by skipping the initialization of those elements.
 */
void sqlite3BtreeCursorZero(BtCursor *p){
	// TODO : Implement
	assert(0);

	//memset(p, 0, offsetof(BtCursor, iPage));
}

/*
 ** Set the cached rowid value of every cursor in the same database file
 ** as pCur and having the same root page number as pCur.  The value is
 ** set to iRowid.
 **
 ** Only positive rowid values are considered valid for this cache.
 ** The cache is initialized to zero, indicating an invalid cache.
 ** A btree will work fine with zero or negative rowids.  We just cannot
 ** cache zero or negative rowids, which means tables that use zero or
 ** negative rowids might run a little slower.  But in practice, zero
 ** or negative rowids are very uncommon so this should not be a problem.
 */
void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
	// TODO : Implement
	assert(0);
	/*
	BtCursor *p;
	for(p=pCur->pBt->pCursor; p; p=p->pNext){
		if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
	}
	*/
}

/*
 ** Return the cached rowid for the given cursor.  A negative or zero
 ** return value indicates that the rowid cache is invalid and should be
 ** ignored.  If the rowid cache has never before been set, then a
 ** zero is returned.
 */
sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
	// TODO : Implement
	assert(0);

	//return pCur->cachedRowid;
	return -1;
}

/*
 ** Close a cursor.  The read lock on the database file is released
 ** when the last cursor is closed.
 */
int sqlite3BtreeCloseCursor(BtCursor *pCur){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

#ifndef NDEBUG  /* The next routine used only within assert() statements */
/*
 ** Return true if the given BtCursor is valid.  A valid cursor is one
 ** that is currently pointing to a row in a (non-empty) table.
 ** This is a verification routine is used only within assert() statements.
 */
int sqlite3BtreeCursorIsValid(BtCursor *pCur){
	// TODO : Implement
	assert(0);
	
	//return pCur && pCur->eState==CURSOR_VALID;
	return -1;
}
#endif /* NDEBUG */

/*
 ** Set *pSize to the size of the buffer needed to hold the value of
 ** the key for the current entry.  If the cursor is not pointing
 ** to a valid entry, *pSize is set to 0. 
 **
 ** For a table with the INTKEY flag set, this routine returns the key
 ** itself, not the number of bytes in the key.
 **
 ** The caller must position the cursor prior to invoking this routine.
 ** 
 ** This routine cannot fail.  It always returns SQLITE_OK.  
 */
int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);

	// *pSize = pCur->info.nKey;
	
	return rc;
}

/*
 ** Set *pSize to the number of bytes of data in the entry the
 ** cursor currently points to.
 **
 ** The caller must guarantee that the cursor is pointing to a non-NULL
 ** valid entry.  In other words, the calling procedure must guarantee
 ** that the cursor has Cursor.eState==CURSOR_VALID.
 **
 ** Failure is not possible.  This function always returns SQLITE_OK.
 ** It might just as well be a procedure (returning void) but we continue
 ** to return an integer result code for historical reasons.
 */
int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	// *pSize = pCur->info.nData;
	
	return rc;
}

/*
 ** Read part of the key associated with cursor pCur.  Exactly
 ** "amt" bytes will be transfered into pBuf[].  The transfer
 ** begins at "offset".
 **
 ** The caller must ensure that pCur is pointing to a valid row
 ** in the table.
 **
 ** Return SQLITE_OK on success or an error code if anything goes
 ** wrong.  An error is returned if "offset+amt" is larger than
 ** the available payload.
 */
int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
		
	return rc;
}

/*
 ** Read part of the data associated with cursor pCur.  Exactly
 ** "amt" bytes will be transfered into pBuf[].  The transfer
 ** begins at "offset".
 **
 ** Return SQLITE_OK on success or an error code if anything goes
 ** wrong.  An error is returned if "offset+amt" is larger than
 ** the available payload.
 */
int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	// return SQLITE_ABORT;
	return rc;
}

/*
 ** For the entry that cursor pCur is point to, return as
 ** many bytes of the key or data as are available on the local
 ** b-tree page.  Write the number of available bytes into *pAmt.
 **
 ** The pointer returned is ephemeral.  The key/data may move
 ** or be destroyed on the next call to any Btree routine,
 ** including calls from other threads against the same cache.
 ** Hence, a mutex on the BtShared should be held prior to calling
 ** this routine.
 **
 ** These routines is used to get quick access to key and data
 ** in the common case where no overflow pages are used.
 */
const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
	const void *p = 0;
	
	// TODO : Implement
	assert(0);
	//p = (const void*)fetchPayload(pCur, pAmt, 0);

	return p;
}
const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
	const void *p = 0;
	
	// TODO : Implement
	assert(0);
	//p = (const void*)fetchPayload(pCur, pAmt, 1);
	
	return p;
}


/* Move the cursor to the first entry in the table.  Return SQLITE_OK
 ** on success.  Set *pRes to 0 if the cursor actually points to something
 ** or set *pRes to 1 if the table is empty.
 */
int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/* Move the cursor to the last entry in the table.  Return SQLITE_OK
 ** on success.  Set *pRes to 0 if the cursor actually points to something
 ** or set *pRes to 1 if the table is empty.
 */
int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/* Move the cursor so that it points to an entry near the key 
 ** specified by pIdxKey or intKey.   Return a success code.
 **
 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
 ** must be NULL.  For index tables, pIdxKey is used and intKey
 ** is ignored.
 **
 ** If an exact match is not found, then the cursor is always
 ** left pointing at a leaf page which would hold the entry if it
 ** were present.  The cursor might point to an entry that comes
 ** before or after the key.
 **
 ** An integer is written into *pRes which is the result of
 ** comparing the key with the entry to which the cursor is 
 ** pointing.  The meaning of the integer written into
 ** *pRes is as follows:
 **
 **     *pRes<0      The cursor is left pointing at an entry that
 **                  is smaller than intKey/pIdxKey or if the table is empty
 **                  and the cursor is therefore left point to nothing.
 **
 **     *pRes==0     The cursor is left pointing at an entry that
 **                  exactly matches intKey/pIdxKey.
 **
 **     *pRes>0      The cursor is left pointing at an entry that
 **                  is larger than intKey/pIdxKey.
 **
 */
int sqlite3BtreeMovetoUnpacked(
							   BtCursor *pCur,          /* The cursor to be moved */
							   UnpackedRecord *pIdxKey, /* Unpacked index key */
							   i64 intKey,              /* The table key */
							   int biasRight,           /* If true, bias the search to the high end */
							   int *pRes                /* Write search results here */
							   ){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}


/*
 ** Return TRUE if the cursor is not pointing at an entry of the table.
 **
 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
 ** past the last entry in the table or sqlite3BtreePrev() moves past
 ** the first entry.  TRUE is also returned if the table is empty.
 */
int sqlite3BtreeEof(BtCursor *pCur){
	// TODO : Implement
	assert(0);
	//return (CURSOR_VALID!=pCur->eState);
	return -1;
}

/*
 ** Advance the cursor to the next entry in the database.  If
 ** successful then set *pRes=0.  If the cursor
 ** was already pointing to the last entry in the database before
 ** this routine was called, then set *pRes=1.
 */
int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}


/*
 ** Step the cursor to the back to the previous entry in the database.  If
 ** successful then set *pRes=0.  If the cursor
 ** was already pointing to the first entry in the database before
 ** this routine was called, then set *pRes=1.
 */
int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	//*pRes = 1;
	//*pRes = 0;
	
	return rc;
}

/*
 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
 ** and the data is given by (pData,nData).  The cursor is used only to
 ** define what table the record should be inserted into.  The cursor
 ** is left pointing at a random location.
 **
 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
 **
 ** If the seekResult parameter is non-zero, then a successful call to
 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
 ** been performed. seekResult is the search result returned (a negative
 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
 ** a positive value if pCur points at an etry that is larger than 
 ** (pKey, nKey)). 
 **
 ** If the seekResult parameter is non-zero, then the caller guarantees that
 ** cursor pCur is pointing at the existing copy of a row that is to be
 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
 ** point to any entry or to no entry at all and so this function has to seek
 ** the cursor before the new key can be inserted.
 */
int sqlite3BtreeInsert(
					   BtCursor *pCur,                /* Insert data into the table of this cursor */
					   const void *pKey, i64 nKey,    /* The key of the new record */
					   const void *pData, int nData,  /* The data of the new record */
					   int nZero,                     /* Number of extra 0 bytes to append to data */
					   int appendBias,                /* True if this is likely an append */
					   int seekResult                 /* Result of prior MovetoUnpacked() call */
					   ){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Delete the entry that the cursor is pointing to.  The cursor
 ** is left pointing at a arbitrary location.
 */
int sqlite3BtreeDelete(BtCursor *pCur){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Create a new BTree table.  Write into *piTable the page
 ** number for the root page of the new table.
 **
 ** The type of type is determined by the flags parameter.  Only the
 ** following values of flags are currently in use.  Other values for
 ** flags might not work:
 **
 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
 **     BTREE_ZERODATA                  Used for SQL indices
 */
int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Delete all information from a single table in the database.  iTable is
 ** the page number of the root of the table.  After this routine returns,
 ** the root page is empty, but still exists.
 **
 ** This routine will fail with SQLITE_LOCKED if there are any open
 ** read cursors on the table.  Open write cursors are moved to the
 ** root of the table.
 **
 ** If pnChange is not NULL, then table iTable must be an intkey table. The
 ** integer value pointed to by pnChange is incremented by the number of
 ** entries in the table.
 */
int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Erase all information in a table and add the root of the table to
 ** the freelist.  Except, the root of the principle table (the one on
 ** page 1) is never added to the freelist.
 **
 ** This routine will fail with SQLITE_LOCKED if there are any open
 ** cursors on the table.
 **
 ** If AUTOVACUUM is enabled and the page at iTable is not the last
 ** root page in the database file, then the last root page 
 ** in the database file is moved into the slot formerly occupied by
 ** iTable and that last slot formerly occupied by the last root page
 ** is added to the freelist instead of iTable.  In this say, all
 ** root pages are kept at the beginning of the database file, which
 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
 ** page number that used to be the last root page in the file before
 ** the move.  If no page gets moved, *piMoved is set to 0.
 ** The last root page is recorded in meta[3] and the value of
 ** meta[3] is updated by this procedure.
 */
int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}


/*
 ** This function may only be called if the b-tree connection already
 ** has a read or write transaction open on the database.
 **
 ** Read the meta-information out of a database file.  Meta[0]
 ** is the number of free pages currently in the database.  Meta[1]
 ** through meta[15] are available for use by higher layers.  Meta[0]
 ** is read-only, the others are read/write.
 ** 
 ** The schema layer numbers meta values differently.  At the schema
 ** layer (and the SetCookie and ReadCookie opcodes) the number of
 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
 */
void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
	
	// TODO : Implement
	assert(0);
	
	//*pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
}

/*
 ** Write meta-information back into the database.  Meta[0] is
 ** read-only and may not be written.
 */
int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);

	/*
	rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
	if( rc==SQLITE_OK ){
		//put4byte(&pP1[36 + idx*4], iMeta);
	}
	*/
	
	return rc;
}

#ifndef SQLITE_OMIT_BTREECOUNT
/*
 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
 ** number of entries in the b-tree and write the result to *pnEntry.
 **
 ** SQLITE_OK is returned if the operation is successfully executed. 
 ** Otherwise, if an error is encountered (i.e. an IO error or database
 ** corruption) an SQLite error code is returned.
 */
int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}
#endif

/*
 ** Return the pager associated with a BTree.  This routine is used for
 ** testing and debugging only.
 */
Pager *sqlite3BtreePager(Btree *p){
    // TODO : Implement
	
	assert(0);
	
//	return p->pBt->pPager;
	return NULL;
}

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/*
 ** This routine does a complete check of the given BTree file.  aRoot[] is
 ** an array of pages numbers were each page number is the root page of
 ** a table.  nRoot is the number of entries in aRoot.
 **
 ** A read-only or read-write transaction must be opened before calling
 ** this function.
 **
 ** Write the number of error seen in *pnErr.  Except for some memory
 ** allocation errors,  an error message held in memory obtained from
 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
 ** returned.  If a memory allocation error occurs, NULL is returned.
 */
char *sqlite3BtreeIntegrityCheck(
								 Btree *p,     /* The btree to be checked */
								 int *aRoot,   /* An array of root pages numbers for individual trees */
								 int nRoot,    /* Number of entries in aRoot[] */
								 int mxErr,    /* Stop reporting errors after this many */
								 int *pnErr    /* Write number of errors seen to this variable */
								 ){
	// TODO : Implement
	assert(0);
	
	return 0;
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

/*
 ** Return the full pathname of the underlying database file.
 **
 ** The pager filename is invariant as long as the pager is
 ** open so it is safe to access without the BtShared mutex.
 */
const char *sqlite3BtreeGetFilename(Btree *p){
	// TODO : Implement
	assert(0);
	//return sqlite3PagerFilename(p->pBt->pPager);

	return 0;
}

/*
 ** Return the pathname of the journal file for this database. The return
 ** value of this routine is the same regardless of whether the journal file
 ** has been created or not.
 **
 ** The pager journal filename is invariant as long as the pager is
 ** open so it is safe to access without the BtShared mutex.
 */
const char *sqlite3BtreeGetJournalname(Btree *p){
	// TODO : Implement
	assert(0);
	//return sqlite3PagerJournalname(p->pBt->pPager);
	return 0;
}

/*
 ** Return non-zero if a transaction is active.
 */
int sqlite3BtreeIsInTrans(Btree *p){
	// TODO : Implement
	assert(0);
	
	//return (p && (p->inTrans==TRANS_WRITE));
	return -1;
}

#ifndef SQLITE_OMIT_WAL
/*
 ** Run a checkpoint on the Btree passed as the first argument.
 **
 ** Return SQLITE_LOCKED if this or any other connection has an open 
 ** transaction on the shared-cache the argument Btree is connected to.
 **
 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 */
int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	// rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
	return rc;
}
#endif

/*
 ** Return non-zero if a read (or write) transaction is active.
 */
int sqlite3BtreeIsInReadTrans(Btree *p){
	// TODO : Implement
	assert(0);
	
	//return p->inTrans!=TRANS_NONE;
	
	return -1;
}

int sqlite3BtreeIsInBackup(Btree *p){
	// TODO : Implement
	assert(0);
	
	// return p->nBackup!=0;

	return -1;
}

/*
 ** This function returns a pointer to a blob of memory associated with
 ** a single shared-btree. The memory is used by client code for its own
 ** purposes (for example, to store a high-level schema associated with 
 ** the shared-btree). The btree layer manages reference counting issues.
 **
 ** The first time this is called on a shared-btree, nBytes bytes of memory
 ** are allocated, zeroed, and returned to the caller. For each subsequent 
 ** call the nBytes parameter is ignored and a pointer to the same blob
 ** of memory returned. 
 **
 ** If the nBytes parameter is 0 and the blob of memory has not yet been
 ** allocated, a null pointer is returned. If the blob has already been
 ** allocated, it is returned as normal.
 **
 ** Just before the shared-btree is closed, the function passed as the 
 ** xFree argument when the memory allocation was made is invoked on the 
 ** blob of allocated memory. This function should not call sqlite3_free()
 ** on the memory, the btree layer does that.
 */
void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
	// TODO : Implement
	assert(0);
	
	/*
	pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
	pBt->xFreeSchema = xFree;
	return pBt->pSchema;
	 */
	return 0;
}

/*
 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
 ** btree as the argument handle holds an exclusive lock on the 
 ** sqlite_master table. Otherwise SQLITE_OK.
 */
int sqlite3BtreeSchemaLocked(Btree *p){
	int rc = SQLITE_OK;

	// TODO : Implement
	assert(0);
	
	//rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
	return rc;
}


#ifndef SQLITE_OMIT_SHARED_CACHE
/*
 ** Obtain a lock on the table whose root page is iTab.  The
 ** lock is a write lock if isWritelock is true or a read lock
 ** if it is false.
 */
int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
	int rc = SQLITE_OK;

	// TODO : Implement
	assert(0);
	
	/*
	if( p->sharable ){
		rc = querySharedCacheTableLock(p, iTab, lockType);
	}
	*/
	return rc;
}
#endif

#ifndef SQLITE_OMIT_INCRBLOB
/*
 ** Argument pCsr must be a cursor opened for writing on an 
 ** INTKEY table currently pointing at a valid table entry. 
 ** This function modifies the data stored as part of that entry.
 **
 ** Only the data content may only be modified, it is not possible to 
 ** change the length of the data stored. If this function is called with
 ** parameters that attempt to write past the end of the existing data,
 ** no modifications are made and SQLITE_CORRUPT is returned.
 */
int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	//rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
	return rc;
}

/* 
 ** Set a flag on this cursor to cache the locations of pages from the 
 ** overflow list for the current row. This is used by cursors opened
 ** for incremental blob IO only.
 **
 ** This function sets a flag only. The actual page location cache
 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
 ** accessPayload() (the worker function for sqlite3BtreeData() and
 ** sqlite3BtreePutData()).
 */
void sqlite3BtreeCacheOverflow(BtCursor *pCur){
	// TODO : Implement
	assert(0);

	//invalidateOverflowCache(pCur);
	//pCur->isIncrblobHandle = 1;
}
#endif

/*
 ** Set both the "read version" (single byte at byte offset 18) and 
 ** "write version" (single byte at byte offset 19) fields in the database
 ** header to iVersion.
 */
int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	//rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
	return rc;
}
/*
 **************************************************************************
 **************************************************************************
 ** 
 ** sqlite3Btree functions ( from btmutex.c )
 ** 
 **************************************************************************
 **************************************************************************
 */

#ifndef SQLITE_OMIT_SHARED_CACHE
#if SQLITE_THREADSAFE

/*
 ** Enter a mutex on the given BTree object.
 **
 ** If the object is not sharable, then no mutex is ever required
 ** and this routine is a no-op.  The underlying mutex is non-recursive.
 ** But we keep a reference count in Btree.wantToLock so the behavior
 ** of this interface is recursive.
 **
 ** To avoid deadlocks, multiple Btrees are locked in the same order
 ** by all database connections.  The p->pNext is a list of other
 ** Btrees belonging to the same database connection as the p Btree
 ** which need to be locked after p.  If we cannot get a lock on
 ** p, then first unlock all of the others on p->pNext, then wait
 ** for the lock to become available on p, then relock all of the
 ** subsequent Btrees that desire a lock.
 */
void sqlite3BtreeEnter(Btree *p){
	// TODO : Implement
	assert(0);
}

/*
 ** Exit the recursive mutex on a Btree.
 */
void sqlite3BtreeLeave(Btree *p){
	// TODO : Implement
	assert(0);
}

#ifndef NDEBUG
/*
 ** Return true if the BtShared mutex is held on the btree, or if the
 ** B-Tree is not marked as sharable.
 **
 ** This routine is used only from within assert() statements.
 */
int sqlite3BtreeHoldsMutex(Btree *p){
	// TODO : Implement
	assert(0);
	
	return -1;
}
#endif


#ifndef SQLITE_OMIT_INCRBLOB
/*
 ** Enter and leave a mutex on a Btree given a cursor owned by that
 ** Btree.  These entry points are used by incremental I/O and can be
 ** omitted if that module is not used.
 */
void sqlite3BtreeEnterCursor(BtCursor *pCur){
	sqlite3BtreeEnter(pCur->pBtree);
}
void sqlite3BtreeLeaveCursor(BtCursor *pCur){
	sqlite3BtreeLeave(pCur->pBtree);
}
#endif /* SQLITE_OMIT_INCRBLOB */


/*
 ** Enter the mutex on every Btree associated with a database
 ** connection.  This is needed (for example) prior to parsing
 ** a statement since we will be comparing table and column names
 ** against all schemas and we do not want those schemas being
 ** reset out from under us.
 **
 ** There is a corresponding leave-all procedures.
 **
 ** Enter the mutexes in accending order by BtShared pointer address
 ** to avoid the possibility of deadlock when two threads with
 ** two or more btrees in common both try to lock all their btrees
 ** at the same instant.
 */
void sqlite3BtreeEnterAll(sqlite3 *db){
	// TODO : Implement
	assert(0);
	
/*	
	int i;
	Btree *p;
	for(i=0; i<db->nDb; i++){
		p = db->aDb[i].pBt;
	}
*/
}

void sqlite3BtreeLeaveAll(sqlite3 *db){
	// TODO : Implement
	assert(0);
	
	/*	
	 int i;
	 Btree *p;
	 for(i=0; i<db->nDb; i++){
	 p = db->aDb[i].pBt;
	 }
	 */
}

#ifndef NDEBUG
/*
 ** Return true if the current thread holds the database connection
 ** mutex and all required BtShared mutexes.
 **
 ** This routine is used inside assert() statements only.
 */
int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
	// TODO : Implement
	assert(0);
	
	/*	
	 int i;
	 Btree *p;
	 for(i=0; i<db->nDb; i++){
	 p = db->aDb[i].pBt;
	 }
	 
	 sqlite3_mutex_held(p->pBt->mutex)
	 */
	
	return 0;
}
#endif /* NDEBUG */

/*
 ** Add a new Btree pointer to a BtreeMutexArray. 
 ** if the pointer can possibly be shared with
 ** another database connection.
 **
 ** The pointers are kept in sorted order by pBtree->pBt.  That
 ** way when we go to enter all the mutexes, we can enter them
 ** in order without every having to backup and retry and without
 ** worrying about deadlock.
 **
 ** The number of shared btrees will always be small (usually 0 or 1)
 ** so an insertion sort is an adequate algorithm here.
 */
void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
	// TODO : Implement
	assert(0);
}

/*
 ** Enter the mutex of every btree in the array.  This routine is
 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
 ** exited at the end of the same function.
 */
void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
	// TODO : Implement
	assert(0);
}

/*
 ** Leave the mutex of every btree in the group.
 */
void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
	// TODO : Implement
	assert(0);
}

#else
void sqlite3BtreeEnter(Btree *p){
	// TODO : Implement
	assert(0);
	
	p->pBt->db = p->db;
}
void sqlite3BtreeEnterAll(sqlite3 *db){
	// TODO : Implement
	assert(0);
	
	int i;
	for(i=0; i<db->nDb; i++){
		Btree *p = db->aDb[i].pBt;
		if( p ){
			p->pBt->db = p->db;
		}
	}
}
#endif /* if SQLITE_THREADSAFE */
#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */

/*
 **************************************************************************
 **************************************************************************
 ** 
 ** sqlite3Pager functions
 ** 
 **************************************************************************
 **************************************************************************
 */

#include "sqliteInt.h"
#include "wal.h"


/*
 ** Macros for troubleshooting.  Normally turned off
 */
#if 0
int sqlite3PagerTrace=1;  /* True to enable tracing */
#define sqlite3DebugPrintf printf
#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
#else
#define PAGERTRACE(X)
#endif

#define PAGER_OPEN                  0
#define PAGER_READER                1
#define PAGER_WRITER_LOCKED         2
#define PAGER_WRITER_CACHEMOD       3
#define PAGER_WRITER_DBMOD          4
#define PAGER_WRITER_FINISHED       5
#define PAGER_ERROR                 6

/*
 ** The Pager.eLock variable is almost always set to one of the 
 ** following locking-states, according to the lock currently held on
 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 ** This variable is kept up to date as locks are taken and released by
 ** the pagerLockDb() and pagerUnlockDb() wrappers.
 **
 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
 ** the operation was successful. In these circumstances pagerLockDb() and
 ** pagerUnlockDb() take a conservative approach - eLock is always updated
 ** when unlocking the file, and only updated when locking the file if the
 ** VFS call is successful. This way, the Pager.eLock variable may be set
 ** to a less exclusive (lower) value than the lock that is actually held
 ** at the system level, but it is never set to a more exclusive value.
 **
 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
 ** be a few redundant xLock() calls or a lock may be held for longer than
 ** required, but nothing really goes wrong.
 **
 ** The exception is when the database file is unlocked as the pager moves
 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
 ** transition, by the same pager or any other). If the call to xUnlock()
 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
 ** can confuse the call to xCheckReservedLock() call made later as part
 ** of hot-journal detection.
 **
 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
 ** lock held by this process or any others". So xCheckReservedLock may 
 ** return true because the caller itself is holding an EXCLUSIVE lock (but
 ** doesn't know it because of a previous error in xUnlock). If this happens
 ** a hot-journal may be mistaken for a journal being created by an active
 ** transaction in another process, causing SQLite to read from the database
 ** without rolling it back.
 **
 ** To work around this, if a call to xUnlock() fails when unlocking the
 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
 ** is only changed back to a real locking state after a successful call
 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
 ** lock on the database file before attempting to roll it back. See function
 ** PagerSharedLock() for more detail.
 **
 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
 ** PAGER_OPEN state.
 */
#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)


/*
 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
 ** This could conceivably cause corruption following a power failure on
 ** such a system. This is currently an undocumented limit.
 */
#define MAX_SECTOR_SIZE 0x10000

/*
 ** An instance of the following structure is allocated for each active
 ** savepoint and statement transaction in the system. All such structures
 ** are stored in the Pager.aSavepoint[] array, which is allocated and
 ** resized using sqlite3Realloc().
 */
typedef struct PagerSavepoint PagerSavepoint;
struct PagerSavepoint {
    int dummy;
};

struct Pager {
	sqlite3_vfs *pVfs;          /* OS functions to use for IO */
	sqlite3_file *lfd;          /* File descriptor for log */
	PagerSavepoint *aSavepoint; /* Array of active savepoints */
	int nSavepoint;             /* Number of elements in aSavepoint[] */
};

/*
 ** The following global variables hold counters used for
 ** testing purposes only.  These variables do not exist in
 ** a non-testing build.  These variables are not thread-safe.
 */
#ifdef SQLITE_TEST
int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
# define PAGER_INCR(v)  v++
#else
# define PAGER_INCR(v)
#endif


/*
 ** The maximum legal page number is (2^31 - 1).
 */
#define PAGER_MAX_PGNO 2147483647

/*
 ** The following global variable is incremented whenever the library
 ** attempts to open a temporary file.  This information is used for
 ** testing and analysis only.  
 */
#ifdef SQLITE_TEST
int sqlite3_opentemp_count = 0;
#endif



/*
 ** The following set of routines are used to disable the simulated
 ** I/O error mechanism.  These routines are used to avoid simulated
 ** errors in places where we do not care about errors.
 **
 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
 ** and generate no code.
 */
#ifdef SQLITE_TEST
extern int sqlite3_io_error_pending;
extern int sqlite3_io_error_hit;
static int saved_cnt;
void disable_simulated_io_errors(void){
	saved_cnt = sqlite3_io_error_pending;
	sqlite3_io_error_pending = -1;
}
void enable_simulated_io_errors(void){
	sqlite3_io_error_pending = saved_cnt;
}
#else
# define disable_simulated_io_errors()
# define enable_simulated_io_errors()
#endif

#if !defined(NDEBUG) || defined(SQLITE_TEST)
/*
 ** Return the page number for page pPg.
 */
Pgno sqlite3PagerPagenumber(DbPage *pPg){

	// TODO : Implement
	assert(0);
	//return pPg->pgno;
	return -1;
}
#endif



/*
 ** Begin a write-transaction on the specified pager object. If a 
 ** write-transaction has already been opened, this function is a no-op.
 **
 ** If the exFlag argument is false, then acquire at least a RESERVED
 ** lock on the database file. If exFlag is true, then acquire at least
 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
 ** functions need be called.
 **
 ** If the subjInMemory argument is non-zero, then any sub-journal opened
 ** within this transaction will be opened as an in-memory file. This
 ** has no effect if the sub-journal is already opened (as it may be when
 ** running in exclusive mode) or if the transaction does not require a
 ** sub-journal. If the subjInMemory argument is zero, then any required
 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
 ** or using a temporary file otherwise.
 */

int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
	int rc = SQLITE_OK;

	// TODO : Implement
	assert(0);

	return rc;
}

/*
 ** Sync the database file to disk. This is a no-op for in-memory databases
 ** or pages with the Pager.noSync flag set.
 **
 ** If successful, or if called on a pager for which it is a no-op, this
 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
 */
int sqlite3PagerSync(Pager *pPager){
	int rc = SQLITE_OK;

	// TODO : Implement
	assert(0);
	
	// rc = sqlite3OsSync(pPager->lfd, pPager->syncFlags);
	
	return rc;
}

/*
 ** This function may only be called while a write-transaction is active in
 ** rollback. If the connection is in WAL mode, this call is a no-op. 
 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
 ** the database file, an attempt is made to obtain one.
 **
 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
 ** returned.
 */
int sqlite3PagerExclusiveLock(Pager *pPager){
	int rc = SQLITE_OK;

	// TODO : Implement
	assert(0);
	
	return rc;
}


/*
 ** If a write transaction is open, then all changes made within the 
 ** transaction are reverted and the current write-transaction is closed.
 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
 ** state if an error occurs.
 **
 ** If the pager is already in PAGER_ERROR state when this function is called,
 ** it returns Pager.errCode immediately. No work is performed in this case.
 **
 ** Otherwise, in rollback mode, this function performs two functions:
 **
 **   1) It rolls back the journal file, restoring all database file and 
 **      in-memory cache pages to the state they were in when the transaction
 **      was opened, and
 **
 **   2) It finalizes the journal file, so that it is not used for hot
 **      rollback at any point in the future.
 **
 ** Finalization of the journal file (task 2) is only performed if the 
 ** rollback is successful.
 **
 ** In WAL mode, all cache-entries containing data modified within the
 ** current transaction are either expelled from the cache or reverted to
 ** their pre-transaction state by re-reading data from the database or
 ** WAL files. The WAL transaction is then closed.
 */
int sqlite3PagerRollback(Pager *pPager){
	int rc = SQLITE_OK;                  /* Return code */

	// TODO : Implement
	assert(0);
	
	return rc;
}

/*
 ** Return the approximate number of bytes of memory currently
 ** used by the pager and its associated cache.
 */
int sqlite3PagerMemUsed(Pager *pPager){
	// TODO : Implement
	assert(0);
	
	return -1;
}

#ifdef SQLITE_TEST
/*
 ** This routine is used for testing and analysis only.
 */
int *sqlite3PagerStats(Pager *pPager){
	static int a[11];
	// TODO : Implement
	assert(0);
	return a;
}
#endif

/*
 ** Return true if this is an in-memory pager.
 */
int sqlite3PagerIsMemdb(Pager *pPager){
	return 0;
}

/*
 ** Return the full pathname of the database file.
 */
const char *sqlite3PagerFilename(Pager *pPager){
	// TODO : Implement
	assert(0);

	//return pPager->zFilename;
	return 0;
}

/*
 ** Return the file handle for the database file associated
 ** with the pager.  This might return NULL if the file has
 ** not yet been opened.
 */
sqlite3_file *sqlite3PagerFile(Pager *pPager){
	// TODO : Implement
	assert(0);
	
	//return pPager->lfd;
	return 0;
}

/*
 ** Get/set the locking-mode for this pager. Parameter eMode must be one
 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
 ** the locking-mode is set to the value specified.
 **
 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
 ** locking-mode.
 */
int sqlite3PagerLockingMode(Pager *pPager, int eMode){

	// TODO : Implement
	assert(0);
	
	/*
	if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
		pPager->exclusiveMode = (u8)eMode;
	}
	return (int)pPager->exclusiveMode;
	 */
	return -1;
}

/*
 ** Set the journal-mode for this pager. Parameter eMode must be one of:
 **
 **    PAGER_JOURNALMODE_DELETE
 **    PAGER_JOURNALMODE_TRUNCATE
 **    PAGER_JOURNALMODE_PERSIST
 **    PAGER_JOURNALMODE_OFF
 **    PAGER_JOURNALMODE_MEMORY
 **    PAGER_JOURNALMODE_WAL
 **
 ** The journalmode is set to the value specified if the change is allowed.
 ** The change may be disallowed for the following reasons:
 **
 **   *  An in-memory database can only have its journal_mode set to _OFF
 **      or _MEMORY.
 **
 **   *  Temporary databases cannot have _WAL journalmode.
 **
 ** The returned indicate the current (possibly updated) journal-mode.
 */
int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
	// TODO : Implement
	assert(0);
	
	// return (int)pPager->journalMode;
	return -1;
}

/*
 ** Return the current journal mode.
 */
int sqlite3PagerGetJournalMode(Pager *pPager){
	// TODO : Implement
	assert(0);
	
	// return (int)pPager->journalMode;
	return -1;
}

/*
 ** Return TRUE if the pager is in a state where it is OK to change the
 ** journalmode.  Journalmode changes can only happen when the database
 ** is unmodified.
 */
int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
	// TODO : Implement
	assert(0);

	/*
	if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
	if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
	return 1;
	 */
	return -1;
}

/*
 ** Get/set the size-limit used for persistent journal files.
 **
 ** Setting the size limit to -1 means no limit is enforced.
 ** An attempt to set a limit smaller than -1 is a no-op.
 */
i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
	// TODO : Implement
	assert(0);
	
	/*
	if( iLimit>=-1 ){
		pPager->journalSizeLimit = iLimit;
	}
	return pPager->journalSizeLimit;
	*/
	return -1;
}

#ifndef SQLITE_OMIT_WAL
int sqlite3PagerWalCallback(Pager *pPager){
	int rc = SQLITE_OK;                  /* Return code */
	
	// TODO : Implement
	assert(0);
	
	// return sqlite3WalCallback(pPager->pWal);
	return rc;
}

/*
 ** Return true if the underlying VFS for the given pager supports the
 ** primitives necessary for write-ahead logging.
 */
int sqlite3PagerWalSupported(Pager *pPager){
	// TODO : Implement
	assert(0);
	
	/*
	const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
	return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
	 */
	return 0;
}

/*
 ** This function is called to close the connection to the log file prior
 ** to switching from WAL to rollback mode.
 **
 ** Before closing the log file, this function attempts to take an 
 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
 ** If successful, the EXCLUSIVE lock is not released before returning.
 */
int sqlite3PagerCloseWal(Pager *pPager){
	int rc = SQLITE_OK;
	
	// TODO : Implement
	assert(0);
	
	return rc;
}

#ifdef SQLITE_HAS_CODEC
/*
 ** This function is called by the wal module when writing page content
 ** into the log file.
 **
 ** This function returns a pointer to a buffer containing the encrypted
 ** page content. If a malloc fails, this function may return NULL.
 */
void *sqlite3PagerCodec(PgHdr *pPg){

	// TODO : Implement
	assert(0);

	/*
	void *aData = 0;
	CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
	return aData;
	 */
	return 0;
}
#endif /* SQLITE_HAS_CODEC */

#endif /* !SQLITE_OMIT_WAL */


/*
 **************************************************************************
 **************************************************************************
 ** 
 ** sqlite3Pcache functions
 ** 
 **************************************************************************
 **************************************************************************
 */
/*
 ** A complete page cache is an instance of this structure.
 */
struct PCache {
	sqlite3_pcache *pCache;             /* Pluggable cache module */
};

/*
 ** Some of the assert() macros in this code are too expensive to run
 ** even during normal debugging.  Use them only rarely on long-running
 ** tests.  Enable the expensive asserts using the
 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
 */
#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
# define expensive_assert(X)  assert(X)
#else
# define expensive_assert(X)
#endif


void sqlite3PcacheShutdown(void){
	// TODO : Implement
	assert(0);
}

#ifdef SQLITE_TEST
/*
 ** Get the suggested cache-size value.
 */
int sqlite3PcacheGetCachesize(PCache *pCache){
	assert(0);
	//return pCache->nMax;
	return -1;
}
#endif

/*
 **************************************************************************
 **************************************************************************
 ** 
 ** sqlite3Pcache functions ( from pcache1.c )
 ** (implements the sqlite3_pcache interface)
 ** 
 **************************************************************************
 **************************************************************************
 */

typedef struct PCache1 PCache1;

/* Each page cache is an instance of the following object.  Every
 ** open database file (including each in-memory database and each
 ** temporary or transient database) has a single page cache which
 ** is an instance of this object.
 **
 ** Pointers to structures of this type are cast and returned as 
 ** opaque sqlite3_pcache* handles.
 */
struct PCache1 {
	int dummy;
};

/******************************************************************************/
/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/

/*
 ** This function is called during initialization if a static buffer is 
 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
 ** enough to contain 'n' buffers of 'sz' bytes each.
 **
 ** This routine is called from sqlite3_initialize() and so it is guaranteed
 ** to be serialized already.  There is no need for further mutexing.
 */
void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
	// TODO : Implement
	assert(0);
}

/*
 ** This function is called during initialization (sqlite3_initialize()) to
 ** install the default pluggable cache module, assuming the user has not
 ** already provided an alternative.
 */
void sqlite3PCacheSetDefault(void){
	// TODO : Implement
	assert(0);
	
	//sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
}

#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
/*
 ** This function is called to free superfluous dynamically allocated memory
 ** held by the pager system. Memory in use by any SQLite pager allocated
 ** by the current thread may be sqlite3_free()ed.
 **
 ** nReq is the number of bytes of memory required. Once this much has
 ** been released, the function returns. The return value is the total number 
 ** of bytes of memory released.
 */
int sqlite3PcacheReleaseMemory(int nReq){
	int nFree = 0;
	
	// TODO : Implement
	assert(0);
	
	return nFree;
}
#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */

#ifdef SQLITE_TEST
/*
 ** This function is used by test procedures to inspect the internal state
 ** of the global cache.
 */
void sqlite3PcacheStats(
						int *pnCurrent,      /* OUT: Total number of pages cached */
						int *pnMax,          /* OUT: Global maximum cache size */
						int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
						int *pnRecyclable    /* OUT: Total number of pages available for recycling */
						){
	// TODO : Implement
	assert(0);
	
	/*
	*pnCurrent = pcache1.grp.nCurrentPage;
	*pnMax = pcache1.grp.nMaxPage;
	*pnMin = pcache1.grp.nMinPage;
	*pnRecyclable = nRecyclable;
	 */
}
#endif


